package 字符串拼接;

import java.util.ArrayList;
import java.util.List;


import org.junit.Test;
//用+的方式效率最差，concat由于是内部机制实现，比+的方式好了不少。
//StringBuilder 和StringBuilder的速度较快
public class TestString {
	//private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Test
    public void testPlus() {
        String s = "";
        long ts = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            s = s + String.valueOf(i);
        }
        long te = System.currentTimeMillis();
        //logger.info("+ cost {} ms", te - ts);
        long result =te-ts;
        System.out.println("+:" +result);
    }
    @Test
    public void testConcat() {
        String s = "";
        long ts = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            s = s.concat(String.valueOf(i));
        }
        long te = System.currentTimeMillis();
        //logger.info("concat cost {} ms", te - ts);
        long result =te-ts;
        System.out.println("concat:" +result);
    }
//    @Test
//    public void testJoin() {
//        List<String> list = new ArrayList<String>();
//        long ts = System.currentTimeMillis();
//        for (int i = 0; i < 10000; i++) {
//            list.add(String.valueOf(i));
//        }
//        StringUtils.join(list, "");
//        long te = System.currentTimeMillis();
//        logger.info("StringUtils.join cost {} ms", te - ts);
//    }
    @Test
    public void testStringBuffer() {
        StringBuffer sb = new StringBuffer();
        long ts = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            sb.append(String.valueOf(i));
        }
        sb.toString();
        long te = System.currentTimeMillis();
        //logger.info("StringBuffer cost {} ms", te - ts);
        long result =te-ts;
        System.out.println("StringBuffer.append:" +result);
    }
    @Test
    public void testStringBuilder() {
        StringBuilder sb = new StringBuilder();
        long ts = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            sb.append(String.valueOf(i));
        }
        sb.toString();
        long te = System.currentTimeMillis();
        //logger.info("StringBuilder cost {} ms", te - ts);
        long result =te-ts;
        System.out.println("StringBuilder.append:" +result);
    }
}
